import java.util.List;

import javax.naming.InitialContext;
import javax.persistence.EntityManager;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import entities.Pais;

public class TestHibernate {

	private static SessionFactory factory;
	private static Session session;

	public static void main(String[] args) {

		 
//		 String userHomeDir = System.getProperty("user.home", ".");
//		 String systemDir = userHomeDir + "/.addressbook";
//		 System.setProperty("derby.system.home", systemDir);
		//System.out.println(System.getProperty("derby.system.home"));
		try {
			factory = new Configuration().configure().buildSessionFactory();
		} catch (Throwable ex) {
			System.err.println("Failed to create sessionFactory object." + ex);
			throw new ExceptionInInitializerError(ex);
		}
		TestHibernate ME = new TestHibernate();

		/* Add few employee records in database */
		 Integer empID1 = ME.addEmployee("cde2");
		 Integer empID2 = ME.addEmployee("concepcion2");

		try {
			session = factory.openSession();
			Transaction tx = session.beginTransaction();
			try {

				Pais p2 = new Pais();
				p2.setNombre2("asuncion2");
				session.save(p2);

				Query q = session.createQuery("from " + Pais.class.getName());
				List list = q.list();
				// LOG.info("Query came back with " + list.size() + " results");
				for (Object row : list) {
					// LOG.debug(row.toString());
				}

				tx.commit();
				tx = null;
			} finally {
				if (tx != null) {
					tx.rollback();
					tx = null;
				}
			}
		} finally {
			if (session != null && session.isOpen()) {
				session.close();
			}
		}

	}

	/* Method to CREATE an employee in the database */
	public Integer addEmployee(String lname) {
		Session session = factory.openSession();
		Transaction tx = null;
		Integer employeeID = null;
		try {
			tx = session.beginTransaction();
			Pais employee = new Pais();
			employee.setNombre2(lname);
			// employee.setDescripcion(lname);
			employeeID = (Integer) session.save(employee);
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return employeeID;
	}
	
}
